home *** CD-ROM | disk | FTP | other *** search
- Path: atglab.bls.com!Alun.Champion
- From: Alun.Champion@bridge.bst.bls.com (Alun Champion)
- Newsgroups: comp.lang.c++
- Subject: Re: Newbie question...
- Date: 09 Jan 1996 21:35:35 GMT
- Organization: Computer People Inc.
- Message-ID: <ALUN.CHAMPION.96Jan9163535@g7240065.bridge.bst.bls.com>
- References: <30EDB825.70A8@rgs.navsea.navy.mil>
- NNTP-Posting-Host: bstfirewall.bst.bls.com
-
-
- : Dan Loomis wrote:
- :>
- :> Is there any way (or to put it a better way, acceptable), to return a
- :> member function reference in order to access private class data?
- :>
- :> //For example...
- :>
- :> class clsMyClass
- :> {
- :> private:
- :> int iResult;
- :> public:
- :> [return type] Result([Arg1]);
- :> };
- :>
- :> //the usual function declarations...
- :>
- :> //...so that I can do this?
- :>
- :> main()
- :> {
- :> clsMyClass objMyClass;
- :> int iBuffer;
- :>
- :> iBuffer = objMyClass.Result();
- :>
- :> //and do this...
- :>
- :> objMyClass.Result() = 3;
- :>
- :> //Any guesses where I got this awful idea from?
- :> };
-
- Yes
-
- class clsMyClass
- {
- public:
- int& Result(void)
- { return iResult; }
-
- private:
- int iResult;
- };
-
- This would allow you to do what you want.
-
- :> Is this acceptable programming practice, or should I just define
- :> something like getResult() and setResult(int)?
-
- The reason there would be problems with this is, if at a later stage you
- decide you don't want to keep the state of that variable but calculate
- it then all code that uses these functions breaks.
-
- What you can do is encapsulate this problem in a class say ResultProperty
- [ *Warning untested code - writing straight into editor ;']
-
- class ResultProperty
- {
- public:
- const Property& operator = (int result)
- { result_ = result; return *this; }
- operator int (void)
- { return result_; }
-
- private:
- int result_;
- };
-
- now the clsMyClass becomes
-
- class clsMyClass
- {
- public:
- ResultProperty& Result(void)
- { return result_; }
-
- private:
- ResultProperty result_;
- };
-
- Its use would be as your main i.e: a.Result() = 5;
- At a later stage if you wish to calculate things or get the information
- from somewhere else you can change the ResultProperty class and client
- code will not break.
-
- I am not saying I advocate this solution, but it is better than returning
- a direct reference to state.
-
- Normally I would use function overloading to distinguish between accessor and
- mutator like:
-
- class clsMyClass
- {
- public:
- int result(void)
- { return result_; }
-
- void result(int r)
- { result_ = r; }
- or
- int result(int r)
- { int tmp = result_; result_ = r; return tmp; }
-
- private:
- int result_;
- };
-
- And use it like
-
- int old = cls.result(new);
- ...
- cls.result(old);
-
- Hope this helps
- Regards
-
- -A.
- --
- | A.Champion |
-